package com.qin.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.qin.entity.User;
import com.qin.service.ShoppingService;
import com.qin.service.UserService;
import com.qin.service.impl.ShoppingServiceImpl;
import com.qin.service.impl.UserServiceImpl;

import cn.hutool.log.StaticLog;

/**
 * 用于处理用户登录
 * @author BestRiven
 *
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserService userService = new UserServiceImpl();
	private ShoppingService shoppingService = new ShoppingServiceImpl();
	
	/**
	 * 去登录页
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		StaticLog.debug("前往登录页面");
		
		// 尝试从session中拿user
		HttpSession session = request.getSession();
		Object user = session.getAttribute("user");
		
		// 拿到直接去成功页，没拿到就去登录页
		if(user == null) {
			// 需要判断
			
			request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
		}else {
			response.sendRedirect(request.getContextPath());

		}
	}

	/**
	 * 完成登录操作
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 拿到用户名和密码和用户名是否是邮箱和是否记住密码
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		boolean isEmail = Boolean.parseBoolean(request.getParameter("isEmail"));
		boolean isRemb = Boolean.parseBoolean(request.getParameter("isRemb"));
		
		// 去数据库查
		StaticLog.debug("要登录用户的用户名{}和密码{}和是否是{}", username,password,isEmail);
		
		// 先检查验证码，先从session域中获取真正的验证码,再从请求域中拿要验证的验证码
		HttpSession session = request.getSession();
		String attribute = (String) session.getAttribute("lineCaptcha");
		String verificationCode = request.getParameter("verificationCode");
		
		if(!verificationCode.equalsIgnoreCase(attribute)) { // 不相等
			// 重定向到登录页,并把错误消息放在cookie中
			Cookie vmsg = new Cookie("vmsg","验证码错误！");
			vmsg.setMaxAge(1);
			response.addCookie(vmsg);
			
			response.sendRedirect(request.getContextPath()+"/login");
			return;
		}
		
		// 验证码验证成功！去数据库查询user
		User user = userService.queryUserByNameOrByEmail(username, isEmail);
		
		StaticLog.debug("验证码验证成功！从数据库中查询user{}", user);
		
		// 进行验证
		if(user != null && username.equals(user.getName()) && password.equals(user.getPassword())) {
			// 查到了user还需要设置他的订单数量
			int size = shoppingService.getShoppingItemsByUserId(user.getId()).size();
			session.setAttribute("shoppingNum", size);
			
			// 成功！！放在session域中
			session.setAttribute("user", user);
			
			// 判断是否记住密码,如果是，把名字和密码放入cookie中
			if(isRemb) {
				Cookie name = new Cookie("username", username);
				name.setMaxAge(60*60*24);
				Cookie pwd = new Cookie("password",password);
				pwd.setMaxAge(60*60*24);
				Cookie check = new Cookie("checked","checked");
				check.setMaxAge(60*60*24);
				
				response.addCookie(name);
				response.addCookie(pwd);
				response.addCookie(check);
			}else {
				Cookie name = new Cookie("username", null);
				name.setMaxAge(60*60*24);
				Cookie pwd = new Cookie("password",null);
				pwd.setMaxAge(60*60*24);
				Cookie check = new Cookie("checked",null);
				check.setMaxAge(60*60*24);
				
				response.addCookie(name);
				response.addCookie(pwd);
				response.addCookie(check);
			}
			// 重定向到首页
			response.sendRedirect(request.getContextPath()+"/index");
		}else { // 失败！放入 用户或者用户名或密码错误 消息
			Cookie umsg = new Cookie("umsg","用户名或密码错误!");
			umsg.setMaxAge(1);
			response.addCookie(umsg);
			
			response.sendRedirect(request.getContextPath()+"/login");
		}
	}

}
